import { useState, useMemo, useEffect, useRef } from 'react';
import { Form, Select, Popover, Spin, Tooltip } from 'antd';
import { debounce, uniqBy } from 'lodash';
import Iconfont from '@/components/IconFont';
import AddSelectListModal from './AddSelectListModal';
import { queryFactoryList } from '@/services/common';
import { customTrimFunc } from '@/utils/utils';

const { Option } = Select;

const DynamicStoreSelect = ({ value, resetKey, initStoreList = [], wrapperStyles = {}, styles, handleAllSelect }) => {

  const [storeList, setList] = useState([]);//供应商下拉选项
  const [visible, setVisible] = useState(false);//弹窗显隐
  const [fetching, setFetching] = useState(false);
  const fetchRef = useRef(0);
  const baseList = useRef([]);
  // const outSelected = useRef([]);

  useEffect(() => {
    baseList.current = [];
    if (storeList?.length) {
      setList([]);
    }
  }, [resetKey])

  useEffect(() => {
    if (initStoreList?.length) {
      baseList.current = [...initStoreList];
      setList([...initStoreList]);
    }
  }, [initStoreList])

  const outSelected = useMemo(()=>{
    if(value?.length){
      return baseList.current.filter(item=>value.includes(item.storeId)).map(item=>item.storeId);
    }
    return []
   }, [value])

  const debounceFetcher = () => {
    const loadOptions = (storeName) => {
      if (!storeName?.trim()) return;
      fetchRef.current += 1;
      const fetchId = fetchRef.current;
      setFetching(true);
      queryFactoryList(customTrimFunc({
        storeName,
        size: 50,
        current: 1,
        querySrc: 0
      })).then(({ data, success }) => {
        if (success) {
          if (fetchId !== fetchRef.current) {
            // for fetch callback order
            return;
          }
          setList(data?.records || []);
          setFetching(false);
        }
      });
    };
    return debounce(loadOptions, 600);
  };

  //渲染供应商下拉
  const renderStoreList = useMemo(() => {
    if (storeList?.length) {
      return storeList.map((d) => (
        <Option
          className="smallFontSizeOption"
          key={d.storeId}
          value={d.storeId}
          label={d.storeName}
        >
          <Tooltip title={d.storeName}>
            {d.storeName}
          </Tooltip>
        </Option>))
    } else {
      return '请先批量添加供应商'
    }
  }, [storeList])

  //添加供应商可选项弹窗
  const addSelectListModalProps = {
    visible,
    resetKey,
    outSelected,
    storeList: baseList.current,
    handleOk(arr) {
      baseList.current = arr;
      setList(arr);
      setVisible(false);
      handleAllSelect(arr.reduce((prev, next) => prev.concat(next.storeId), []), arr);
    },
    handleCancel() {
      setVisible(false);
    }
  }

  //供应商选择时打标记
  const handleChangeSelect = (ids) => {
    const arr = storeList.filter(item => ids.includes(item.storeId));
    baseList.current = uniqBy([...baseList.current, ...arr], 'storeId');
    handleAllSelect(ids, baseList.current);
  }

  return (<>
    <div style={{ display: "flex", justifyContent: 'space-between', ...wrapperStyles }}>
      <Select
        allowClear
        showSearch
        mode="multiple"
        maxTagCount='responsive'
        placeholder="请选择供应商"
        filterOption={false}
        value={value}
        onChange={handleChangeSelect}
        onSearch={debounceFetcher()}
        onBlur={() => setList(baseList.current)}
        notFoundContent={fetching ? <Spin size="small" /> : '暂无数据'}
      >
        {renderStoreList}
      </Select>
      <Popover content='点击可操作批量多选供应商进行搜索'>
        <div
          onClick={() => { setVisible(true) }}
          style={{ cursor: 'pointer', display: 'inline-block', width: "32px", position: 'relative', top: styles?.top || '0px' }}
        >
          <Iconfont style={{ fontSize: '12px', cursor: 'pointer', marginLeft: '8px' }} type="icondirect-input"></Iconfont>
        </div>
      </Popover>
    </div>
    <AddSelectListModal {...addSelectListModalProps} />
  </>)
}

export default DynamicStoreSelect;